<?php
namespace Mapi\Controller;
use Think\Controller;

class PushController extends controller {
	protected static $apiUrl = 'http://mobile.appwuhan.com/helper/';
	private $token = '';
	private $rotate = 0;

	public function getToken() {
		$authUrl = self::$apiUrl . 'auth.php';

		$data['username'] = 'phptest';
		$data['password'] = '123456';
        $info = gethttpcurl($authUrl."?".http_build_query($data));
        $json = json_decode($info, true);

        $this->token = $json[0]['token'];
	}

	public function pushArticle($articleId) {
        $articleId = $articleId;// I('get.articleId', 0);
        $b=true;
        $info = M('Article')->alias('ar')
            ->join('__USER_INFO__ ui ON ar.user_id=ui.uid')
            ->where(array('id' => $articleId))->find();
        if(!$info) {
            $message['resultCode'] = 1;
            $message['message'] = '文章不存在';
            $this->ajaxReturn($message);
        }

        $info['content'] = $info['html_content'] ? $info['html_content'] : $info['content'];
        if(!$info['content']) {
            $message['resultCode'] = 1;
            $message['message'] = '文稿内容为空';
            $this->ajaxReturn($message);
        }

        $fileList = M('Attachment')->where(array('aid' => $articleId,'attachstate'=>'1'))->order('sort ASC')->select(); // 文件列表

        $info['content'] = htmlspecialchars_decode($info['content']);

/*        $image_list = array();
        // 筛选出已使用的图片
        if(preg_match_all('/<img data-type="image"(.*?)id="(.*?)" src="(.*?)"/', $info['content'], $img_matchs)) {
            // 将图片的路径过滤出来
            if(!empty($img_matchs[2])) {
                foreach($img_matchs[2] as $k => $v) {
                    $attach_info = M('Attachment')->where(array('attachid' => $v))->find();
                    $image_list[$k] = $attach_info;
                }
            }
        }

        $video_list = array();
        // 筛选出已使用的音频
        if(preg_match_all('/data-videoid="(.*?)"/', $info['content'], $video_matchs)) {
            if(!empty($video_matchs[1])) {
                foreach($video_matchs[1] as $k => $v) {
                    $attach_info = M('Attachment')->where(array('attachid' => $v))->find();
                    $video_list[$k] = $attach_info;
                }
            }
        }


        $fileList = array_merge($image_list, $video_list);*/

        $this->getToken();//获取M2O的账户
        if(!$this->token){
            $message['resultCode'] = -1;
            $message['message'] = 'no token22';
            $this->ajaxReturn($message);
            exit();
        }

        $picids=array();

/*        foreach($fileList as $key=>$val) {
            $file=$val['filepath'] . $val['filename'];
            $temp=explode('.',$file);
            $fileLocal = gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/genTempFile?file=" . $file,array('timeout'=>9999));
            $fileLocal = trim($fileLocal, "\xEF\xBB\xBF");
            if(in_array($temp[count($temp)-1],array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb','mp4', 'mov'))){
                $dd=gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/pushM2oVideo?token={$this->token}&file={$fileLocal}&title={$info['title']}",array('timeout'=>9999));

                $dd = json_decode(trim($dd, "\xEF\xBB\xBF"),true);
                $dd = isset($dd[0])?$dd[0]:$dd;
                $vids[$val['attachid']] = $dd;

            }else{
                $output=gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/pushM2oAttchment?token={$this->token}&file={$fileLocal}",array('timeout'=>9999));
                $output = json_decode(trim($output, "\xEF\xBB\xBF"),true);
                $ids[$val['attachid']] = isset($output[0])?$output[0]:$output;
                $picids[]=$ids[$val['attachid']]['id'].'';
                if($b){
                    $indexpic = $ids[$val['attachid']]['id'];
                    $b=false;
                }
            }
        }*/

		foreach($fileList as $key=>$val) {
            if($val['client_attach_id']) {
                $file=$val['filepath'] . $val['filename'];
                $fileLocal = gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/genTempFile?file=" . $file . '&type=' . $val['type'] . '&ext=' . $val['ext'],array('timeout'=>9999));
                $fileLocal = trim($fileLocal, "\xEF\xBB\xBF");
                if(in_array($val['type'],array('video', 'audio'))){
                    $dd=gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/pushM2oVideo?token={$this->token}&file={$fileLocal}&title={$info['title']}",array('timeout'=>9999));
                    $dd = json_decode(trim($dd, "\xEF\xBB\xBF"),true);
                    $dd = isset($dd[0])?$dd[0]:$dd;
                    $vids[$val['attachid']] = $dd;

                }else{
                    $output=gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/pushM2oAttchment?token={$this->token}&file={$fileLocal}",array('timeout'=>9999));
                    $output = json_decode(trim($output, "\xEF\xBB\xBF"),true);
                    $ids[$val['attachid']] = isset($output[0])?$output[0]:$output;
                    $picids[]=$ids[$val['attachid']]['id'].'';
                    if($b){
                        $indexpic = $ids[$val['attachid']]['id'];
                        $b=false;
                    }
                }                
            } else {
                $file=$val['filepath'] . $val['filename'];
                $temp=explode('.',$file);
                if(in_array($temp[count($temp)-1],array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb','mp4', 'mov'))){
                    $dd=gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/pushM2oVideo?token={$this->token}&file={$file}&title={$info['title']}",array('timeout'=>9999));
                    $dd = json_decode($dd,true);
                    $dd = isset($dd[0])?$dd[0]:$dd;
                }else{
                    $output=gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/pushM2oAttchment?token={$this->token}&file={$file}",array('timeout'=>9999));
                    $output = json_decode($output,true);
                    $ids[$val['attachid']] = isset($output[0])?$output[0]:$output;
                    $picids[]=$ids[$val['attachid']]['id'].'';
                    if($b){
                        $indexpic = $ids[$val['attachid']]['id'];
                        $b=false;
                    }
                }
            }

        }



        $m2oimg='';
        foreach($ids as $val) {
            $info['content'].='<img imageid="' . $val['id'] . '" src="' . $val['path'] . $val['dir'] . $val['filename'] . '" />';
        }


/*        foreach($ids as $key => $val) {
            if(preg_match('/<img([^<>]*?)id="' . $key . '"([^<>]*?)>/i', $info['content'], $match)) {
                $info['content'] = preg_replace('/<img([^<>]*?)id="' . $key . '"([^<>]*?)>/i', '<img imageid="' . $val['id'] . '" src="' . $val['path'] . $val['dir'] . $val['filename'] . '" />', $info['content']);
            }
        }*/



/*        foreach($vids as $key => $val) {
            if(preg_match('/<img([^<>]*?)data\-videoid="' . $key . '"([^<>]*?)>/i', $info['content'], $match)) {
                $info['content'] = preg_replace('/<img([^<>]*?)data\-videoid="' . $key . '"([^<>]*?)>/i', '<img class="image-refer" src="http://img.appwuhan.com/material/sketch_map/livmedia/livmedia/vod_' . $val['id'] . '.png"/>', $info['content']);
                $info['content'] = str_replace(array('<p id="videobg">','<p id="audiobg">'), '<p style="text-align: center">', $info['content']);
            }
        }*/
 // print_r($info['content']);exit;
        //v2.1.1 - start   修改为：有视频的话，标题加 [带视频]
        if(isset($dd['return']) && $dd['return']=='success'){ //$dd为视频上传m2o的返回
            $article['title'] = '[带视频]'.$info['title'];
            if($b){
                $indexpic = null;
                $b=false;
            }
        }else{
            $article['title'] = $info['title'];
        }
        //v2.1.1 -end

        $article['subtitle'] =  $info['subtitle'];
        $article['keywords'] = $info['keywords'];
        $ulist=M('UserInfo')->where(array('uid'=>array('in',$info['author'])))->select();
        $author=array();
        foreach ($ulist as $key => $value) {
            $author[]=$value['realname'];
        }
        $author2=implode(',', $author);
        if(!in_array($info['realname'],$author)){
            $author2=$info['realname'].','.$author2;
        }

        $article['author'] = $author2;
        $article['brief'] = $info['brief'];
        $article['content'] = $info['content'];
        $article['indexpic'] = $indexpic;
        $article['column_id'] = '135';
        $article['access_token'] = $this->token;
        $article['material_id'] = implode(",",array_reverse($picids));

        \Think\Log::record(json_encode($article),'test-article',true);
        $arts = gethttpcurl(self::$apiUrl . 'createContent.php', array('postarr' => $article));
        $arts = json_decode($arts, true);
        if($arts) {
            $message['resultCode'] = 0;
            $message['message'] = '';
            $message['fileList'] = $arts;
        } else {
            $message['resultCode'] = 1;
            $message['message'] = '推送失败';
        }

        // $this->ajaxReturn($message);
        return $message;
    }

	public function pushArticleByLocal($articleId) {
		$articleId = $articleId;// I('get.articleId', 0);
		$b=true;
		$info = M('Article')->alias('ar')
			->join('__USER_INFO__ ui ON ar.user_id=ui.uid')
			->where(array('id' => $articleId))->find();
		if(!$info) {
			$message['resultCode'] = 1;
			$message['message'] = '文章不存在';
			$this->ajaxReturn($message);
		}

		$fileList = M('Attachment')->where(array('aid' => $articleId,'attachstate'=>'1'))->order('sort ASC')->select(); // 文件列表
		$this->getToken();//获取M2O的账户
		if(!$this->token){
			$message['resultCode'] = -1;
			$message['message'] = 'no token22';
			$this->ajaxReturn($message);
			exit();
		}

		$picids=array();

		foreach($fileList as $key=>$val) {
			$file=$val['filepath'] . $val['filename'];
			$temp=explode('.',$file);
			if(in_array($temp[count($temp)-1],array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb','mp4', 'mov'))){
				$dd=gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/pushM2oVideo?token={$this->token}&file={$file}&title={$info['title']}",array('timeout'=>9999));
				$dd = json_decode($dd,true);
				$dd = isset($dd[0])?$dd[0]:$dd;
			}else{
				$output=gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/pushM2oAttchment?token={$this->token}&file={$file}",array('timeout'=>9999));
				$output = json_decode($output,true);
				$ids[$val['attachid']] = isset($output[0])?$output[0]:$output;
				$picids[]=$ids[$val['attachid']]['id'].'';
				if($b){
					$indexpic = $ids[$val['attachid']]['id'];
					$b=false;
				}
			}
		}

		/*v2.1.0
		foreach($ids as $val) {
	         $info['content'] = '<img imageid="' . $val['id'] . '" src="' . $val['path'] . $val['dir'] . $val['filename'] . '" />' . $info['content'];
		}*/


		//v2.1.1 - start   修改为：推送M2O后台图片正序
		$m2oimg='';
		foreach($ids as $val) {
			$info['content'].='<img imageid="' . $val['id'] . '" src="' . $val['path'] . $val['dir'] . $val['filename'] . '" />';
		}
		//v2.1.1 -end
		print_r($info['content']);
		/*v2.1.0
		$article['title'] = $info['title'];
		*/

		//v2.1.1 - start   修改为：有视频的话，标题加 [带视频]
		if(isset($dd['return']) && $dd['return']=='success'){ //$dd为视频上传m2o的返回
			$article['title'] = '[带视频]'.$info['title'];
		}else{
			$article['title'] = $info['title'];
		}
		//v2.1.1 -end

		$article['subtitle'] =  $info['subtitle'];
		$article['keywords'] = $info['keywords'];
		$ulist=M('UserInfo')->where(array('uid'=>array('in',$info['author'])))->select();
		$author=array();
		foreach ($ulist as $key => $value) {
			$author[]=$value['realname'];
		}
		$author2=implode(',', $author);
		if(!in_array($info['realname'],$author)){
			$author2=$info['realname'].','.$author2;
		}

		$article['author'] = $author2;
		$article['brief'] = $info['brief'];
		$article['content'] = $info['content'];
		$article['indexpic'] = $indexpic;
		$article['column_id'] = '135';
		$article['access_token'] = $this->token;
		$article['material_id'] = implode(",",array_reverse($picids));

		$arts = gethttpcurl(self::$apiUrl . 'createContent.php', array('postarr' => $article));
		$arts = json_decode($arts, true);
		if($arts) {
			$message['resultCode'] = 0;
			$message['message'] = '';
			$message['fileList'] = $arts;
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '推送失败';
		}

		// $this->ajaxReturn($message);
		return $message;
	}

	function pp($articleId){
    	sock_get('http://localhost/Mapi/push/pushArticle.html',array('articleId'=>$articleId));
    }






}